﻿using System;
using System.Collections.Generic;
using DreamBuilder.UI.UserControls.DataAccess.Services;
using System.Web;
using DreamBuilder.Core.Container;
using System.Data;
using ePlanet.SingleWell.Models;
using ePlanet.SingleWell.Services;
using System.IO;
using CommonModule;
using ePlanet.SingleWell.Models;

namespace Web.WebDoc
{
    /// <summary>
    /// WebDocHandler 的摘要说明
    /// </summary>
    public class WebDocHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                string attachmentID = context.Request.QueryString["AttachmentID"];
                string DBHelperString = context.Request.QueryString["AttachmentDBHelperString"];

                if (string.IsNullOrEmpty(DBHelperString) || string.IsNullOrEmpty(attachmentID))
                {
                    throw new Exception("参数AttachmentDBHelperString或者AttachmentID不能为空");
                }

                AttachmentModel model = this.GetAttachmentModel(attachmentID, DBHelperString);
                if (model != null)
                {
                    byte[] attachContent = model.AttachmentContent;
                    if (attachmentID != null && attachmentID.Length > 0)
                    {
                        context.Response.Clear();
                        //context.Response.AddHeader("Content-Disposition", "Application/pdf");
                        context.Response.AddHeader("Content-Disposition", "attachment;filename=" + model.AttachmentName);
                        context.Response.AddHeader("Content-Length", attachContent.Length.ToString());
                        context.Response.ContentType = "APPLICATION/OCTET-STREAM";
                        context.Response.BinaryWrite(attachContent);
                        context.Response.Flush();
                        context.Response.End();
                    }
                }
            }
            catch (Exception ex)
            {
                context.Response.Clear();
                context.Response.Write(ex.Message);
                context.Response.End();
            }
        }

        private AttachmentModel GetAttachmentModel(string attachmentID, string DBHelperString)
        {
            IAttachmentService oIAttachmentService = UContainer.Resolve<IAttachmentService>();
            oIAttachmentService.Initialize(DBHelperString);
            return oIAttachmentService.GetAttachmentModelByAttachmentID(attachmentID);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}